<template>
  <div class="page">
    <!-- 顶部 开始 -->
    <div class="top_info">
      <!-- 今日数据、本周数据、本月数据 开始 -->
      <div class="today_info">
        <el-tabs v-model="tabActive">
          <el-tab-pane label="今日数据" name="today">
            <div class="cell_list">
              <div
                class="cell"
                v-for="(item, index) in todayList"
                :key="`today_${index}`"
              >
                <div class="h1">{{ item.name }}</div>
                <div class="h2">
                  {{ item.num ? Number(item.num).toFixed(0) : 0
                  }}{{ showUnit(item.id) }}
                </div>
                <div class="h3">
                  昨日{{ item.yesterday ? Number(item.yesterday).toFixed(0) : 0
                  }}{{ showUnit(item.id) }}
                </div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="本周数据" name="week">
            <div class="cell_list">
              <div
                class="cell"
                v-for="(item, index) in weekDataList"
                :key="`week_${index}`"
              >
                <div class="h1">{{ item.name }}</div>
                <div class="h2">
                  {{ item.num ? Number(item.num).toFixed(0) : 0
                  }}{{ showUnit(item.id) }}
                </div>
                <div class="h3">
                  上周{{ item.yesterday ? Number(item.yesterday).toFixed(0) : 0
                  }}{{ showUnit(item.id) }}
                </div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="本月数据" name="month">
            <div class="cell_list">
              <div
                class="cell"
                v-for="(item, index) in monthDataList"
                :key="`month_${index}`"
              >
                <div class="h1">{{ item.name }}</div>
                <div class="h2">
                  {{ item.num ? Number(item.num).toFixed(0) : 0 }}
                  {{ showUnit(item.id) }}
                  <i
                    :class="`el-icon-caret-${
                      item.status == 1 ? 'bottom cgreen' : 'top cred'
                    }`"
                    v-if="item.status"
                  ></i>
                </div>
                <div class="h3">
                  上月{{ item.yesterday ? Number(item.yesterday).toFixed(0) : 0
                  }}{{ showUnit(item.id) }}
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
        <div class="update_time">
          <span class="time">更新时间：{{ updateTime }}</span>
        </div>
      </div>
      <!-- 今日数据、本周数据、本月数据 end -->

      <!-- 今日任务 开始 -->
      <div class="cell">
        <div class="title"><span>今日任务</span></div>
        <div class="a_list">
          <div
            class="a_box"
            v-for="(item, index) in taskList"
            :key="`todo_${index}`"
            @click="linkUrlEvent(item)"
          >
            <div class="icon">
              <img :src="require('@/assets/images/' + item.icon)" alt="" />
              <div class="dot" v-if="todoInfo[item.id]">
                {{ todoInfo[item.id] }}
              </div>
            </div>
            <div class="name">{{ item.name }}</div>
          </div>
        </div>
        <div class="task_tips">
          <el-popover placement="top-start" width="400" trigger="hover">
            <div class="task_tips_popover">
              <span
                class="tag"
                v-for="(citem, idx) in todoInfo.yesterdayUnfinished || []"
                :key="`citem_${idx}`"
                >{{ citem }}</span
              >
            </div>
            <div class="" slot="reference">
              <span>昨日未完成者：</span>
              <span
                class="tag"
                v-for="(citem, idx) in getUserList(
                  todoInfo.yesterdayUnfinished
                )"
                :key="`citem_hai_${idx}`"
                >{{ citem }}</span
              >
            </div>
          </el-popover>
        </div>
      </div>
      <!-- 今日任务 end -->
    </div>
    <!-- 顶部 end -->

    <!-- 本月目标、常用功能 开始 -->
    <div class="top_info">
      <!-- 本月目标 开始 -->
      <div class="cell month_goal">
        <div class="title">
          <span class="name">本月目标</span>
          <div class="link" @click="openDialog()">
            <span class="sp1">设置目标</span><i class="el-icon-arrow-right"></i>
          </div>
        </div>
        <div class="plan_box">
          <!-- 左边 开始 -->
          <div class="goal_left">
            <!-- 预约人数 开始 -->
            <div class="goal_cell">
              <div class="info">
                <span class="t1">预约人数</span>
                <span class="sp1">{{ targetInfo.actualAppointmentCnt }}</span>
                <span class="sp2">目标：{{ targetInfo.appointmentCnt }}人</span>
              </div>
              <div class="process">
                <el-progress
                  type="circle"
                  :width="78"
                  :stroke-width="6"
                  :percentage="showProcess(targetInfo.appointmentReachRate)"
                  color="#FAB120"
                ></el-progress>
              </div>
            </div>
            <!-- 预约人数 end -->

            <!-- 到店人数 开始 -->
            <div class="goal_cell">
              <div class="info">
                <span class="t1">到店人数</span>
                <span class="sp1">{{ targetInfo.actualArrivedCnt }}</span>
                <span class="sp2">目标：{{ targetInfo.arrivedCnt }}人</span>
              </div>
              <div class="process">
                <el-progress
                  type="circle"
                  :width="78"
                  :stroke-width="6"
                  :percentage="showProcess(targetInfo.arrivedReachRate)"
                  color="#65E0D2"
                ></el-progress>
              </div>
            </div>
            <!-- 到店人数 end -->

            <!-- 成交人数 开始 -->
            <div class="goal_cell">
              <div class="info">
                <span class="t1">成交人数</span>
                <span class="sp1">{{ targetInfo.actualDealCnt }}</span>
                <span class="sp2">目标：{{ targetInfo.dealCnt }}人</span>
              </div>
              <div class="process">
                <el-progress
                  type="circle"
                  :width="78"
                  :stroke-width="6"
                  :percentage="showProcess(targetInfo.dealReachRate)"
                  color="#119EE2"
                ></el-progress>
              </div>
            </div>
            <!-- 成交人数 end -->
          </div>
          <!-- 左边 end -->

          <!-- 右边 开始 -->
          <div class="goal_right">
            <!-- 成交额 开始 -->
            <div class="line">
              <div class="pre">
                <span>成交额</span>
              </div>
              <div class="process">
                <div class="el_progress">
                  <div
                    class="inner"
                    :style="`width:${showProcess(
                      targetInfo.newDealAmountReachRate
                    )}%`"
                  ></div>
                  <span
                    class="sp1"
                    :style="`left:${showProcess(
                      targetInfo.newDealAmountReachRate
                    )}%`"
                    >{{ showNumber(targetInfo.actualNewDealAmount) }}万</span
                  >
                  <span class="sp2"
                    >{{ showProcess(targetInfo.newDealAmountReachRate) }}%</span
                  >
                </div>
              </div>
              <span class="sp2">目标：{{ targetInfo.newDealAmount }}万</span>
            </div>
            <!-- 成交额 end -->

            <!-- 收款额 开始 -->
            <div class="line">
              <div class="pre">
                <span>收款额</span>
              </div>

              <div class="process">
                <div class="el_progress">
                  <div
                    class="inner"
                    :style="`width:${showProcess(
                      targetInfo.collectMoneyReachRate
                    )}%`"
                  ></div>
                  <span
                    class="sp1"
                    :style="`left:${showProcess(
                      targetInfo.collectMoneyReachRate
                    )}%`"
                    >{{ showNumber(targetInfo.actualCollectMoney) }}万</span
                  >
                  <span class="sp2"
                    >{{ showProcess(targetInfo.collectMoneyReachRate) }}%</span
                  >
                </div>
              </div>
              <span class="sp2">目标：{{ targetInfo.collectMoney }}万</span>
            </div>
            <!-- 收款额 开始 -->
          </div>
          <!-- 右边 end -->

          <!-- <div class="task_tips">{{ targetInfo.giftWordsMessage }}</div> -->
        </div>
      </div>
      <!-- 本月目标 end -->

      <!-- 常用功能 开始 -->
      <div class="cell">
        <div class="title"><span>常用功能</span></div>
        <div class="a_list">
          <div
            class="a_box"
            v-for="(item, index) in linkList"
            :key="`link_${index}`"
            @click="linkUrlEvent(item)"
          >
            <div class="icon">
              <img :src="require('@/assets/images/' + item.icon)" alt="" />
            </div>
            <div class="name">{{ item.name }}</div>
          </div>
        </div>
      </div>
      <!-- 常用功能 end -->
    </div>
    <!-- 本月目标、常用功能 end -->

    <!-- 顶部销售看板 开始 -->
    <div class="top_info">
      <!-- 销售看板 开始 -->
      <div class="today_info">
        <div class="title">
          <span class="name">销售看板</span>
        </div>
        <el-table
          class="el_table mt20"
          size="small"
          :data="salesList"
          show-summary
          :summary-method="getSummaries"
          @sort-change="sortChange"
        >
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="部门" prop="department" />
          <el-table-column
            label="今日待到店"
            prop="todayAppointCnt"
            sortable="custom"
          >
            <template slot-scope="{ row }">{{
              row.todayAppointCnt || 0
            }}</template>
          </el-table-column>
          <el-table-column
            label="今日新增预约"
            prop="todayNewAppointCnt"
            sortable="custom"
          >
            <template slot-scope="{ row }">{{
              row.todayNewAppointCnt || 0
            }}</template>
          </el-table-column>
          <el-table-column
            label="今日跟进次数"
            prop="todayFollowCnt"
            sortable="custom"
          >
            <template slot-scope="{ row }">{{
              row.todayFollowCnt || 0
            }}</template>
          </el-table-column>
          <el-table-column
            label="今日跟进人数"
            prop="todayFollowPeople"
            sortable="custom"
          >
            <template slot-scope="{ row }">{{
              row.todayFollowPeople || 0
            }}</template>
          </el-table-column>
          <el-table-column
            label="本月累计预约"
            prop="monthAppointCnt"
            sortable="custom"
          >
            <template slot-scope="{ row }">{{
              row.monthAppointCnt || 0
            }}</template>
          </el-table-column>
          <el-table-column
            label="本月累计跟进次数"
            prop="monthFollowCnt"
            sortable="custom"
          >
            <template slot-scope="{ row }">{{
              row.monthFollowCnt || 0
            }}</template>
          </el-table-column>
          <el-table-column
            label="本月累计跟进人数"
            prop="monthFollowPeople"
            sortable="custom"
          >
            <template slot-scope="{ row }">{{
              row.monthFollowPeople || 0
            }}</template>
          </el-table-column>
          <el-table-column
            label="平均每天跟进人数"
            prop="averageDailyFollowupPeople"
            sortable="custom"
          >
            <template slot-scope="{ row }">{{
              row.averageDailyFollowupPeople
                ? row.averageDailyFollowupPeople.toFixed(1)
                : 0
            }}</template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 销售看板 end -->

      <!-- 本月排行榜 开始 -->
      <div class="cell">
        <div class="title"><span>本月排行榜</span></div>
        <div class="div_tab">
          <div class="tab_head">
            <div class="th">排名</div>
            <div class="th long_th">姓名</div>
            <div
              class="th"
              v-for="(item, index) in thList"
              :key="`th_${index}`"
              :class="orderType == item.id ? 'cblue' : ''"
              @click="thEvent(item, index)"
            >
              {{ item.name
              }}<i
                :class="
                  item.active ? 'el-icon-caret-top' : 'el-icon-caret-bottom'
                "
              ></i>
            </div>
            <!-- <div class="th" :class="orderType == 1?'cblue':''" id="1" @click="thEvent(1)">预约<i :class="orderType == 1?'el-icon-caret-top':'el-icon-caret-bottom'"></i></div>
            <div class="th" :class="orderType == 2?'cblue':''" id="2" @click="thEvent(2)">成交<i :class="orderType == 2?'el-icon-caret-top':'el-icon-caret-bottom'"></i></div>
            <div class="th" :class="orderType == 3?'cblue':''" id="3" @click="thEvent(3)">收款<i :class="orderType == 3?'el-icon-caret-top':'el-icon-caret-bottom'"></i></div> -->
          </div>
          <div
            class="tab_tr"
            v-for="(item, index) in getPreFive(resultList)"
            :key="`tr_td_${index}`"
          >
            <div class="td">
              <img
                :src="iconList[index + 1]"
                class="img"
                alt=""
                v-if="index < 3"
              />
              <span class="serial_number" v-else>{{ index + 1 }}</span>
            </div>
            <div class="td long_th">{{ item.name }}/{{ item.department }}</div>
            <div class="td" :class="orderType == 1 ? 'cblue' : ''">
              {{ item.appointmentCnt }}
            </div>
            <div class="td" :class="orderType == 2 ? 'cblue' : ''">
              {{ item.dealAmount }}
            </div>
            <div class="td" :class="orderType == 3 ? 'cblue' : ''">
              {{ item.collectMoney }}
            </div>
          </div>
          <div
            class="tab_tr ellipsis_tr"
            v-if="resultList && resultList.length > 10"
          >
            <div class="td">
              <span class="">...</span>
            </div>
            <div class="td"></div>
            <div class="td"></div>
            <div class="td"></div>
            <div class="td"></div>
          </div>
          <div
            class="tab_tr"
            v-for="(item, index) in getLastFive(resultList)"
            :key="`last_tr_td_${index}`"
          >
            <div class="td">
              <!-- <img :src="iconList[index + 1]" class="img" alt="" /> -->
              <span class="serial_number">{{ getIndex(item) }}</span>
            </div>
            <div class="td long_th">{{ item.name }}/{{ item.department }}</div>
            <div class="td" :class="orderType == 1 ? 'cblue' : ''">
              {{ item.appointmentCnt }}
            </div>
            <div class="td" :class="orderType == 2 ? 'cblue' : ''">
              {{ item.dealAmount }}
            </div>
            <div class="td" :class="orderType == 3 ? 'cblue' : ''">
              {{ item.collectMoney }}
            </div>
          </div>
        </div>
        <div class="staff_tips">
          您当前成交排名：{{ staffInfo.dealRanking }}位，收款排名：{{
            staffInfo.collectRanking
          }}位
        </div>
      </div>
      <!-- 本月排行榜 end-->
    </div>
    <!-- 顶部销售看板 end -->

    <!-- 转化率  开始 -->
    <div class="today_info change_rate">
      <div class="title">
        <div class="left">
          <span class="name">{{ showRateTime(dealTime) }}月转化率</span>
          <el-date-picker
            v-model="dealTime"
            size="mini"
            type="month"
            placeholder="选择月"
            class="a_input"
            value-format="yyyy-MM"
            @change="getMonthRate"
          >
          </el-date-picker>
        </div>
        <div class="right">
          <span class="time">更新时间：{{ updateTime }}</span>
        </div>
      </div>

      <div class="chart_info">
        <div class="top">
          <div class="tab_head">
            <div class="th first_th"></div>
            <div class="th">我的转化率</div>
            <div class="th">最佳转化率</div>
            <div class="th">平均转化率</div>
          </div>
        </div>
        <div class="bottom">
          <div class="tab_box">
            <div class="tab_tr">
              <div class="td first_td"><div class="td_customer">客户数</div></div>
              <div class="td">
                <div>客户数</div>
                <div class="t1">{{ myRateInfo.customerCnt || 0 }}</div>
              </div>
              <div class="td">
                <div>客户数</div>
                <div class="t1">{{ bestRateInfo.customerCnt || 0 }}</div>
              </div>
              <div class="td">
                <div>客户数</div>
                <div class="t1">{{ meanRateInfo.customerCnt || 0 }}</div>
              </div>
            </div>
            <div class="tab_tr">
              <div class="td first_td"><div class="td_book">客户预约率</div></div>
              <div class="td">
                <div>客户预约率</div>
                <div class="t1">
                  {{
                    myRateInfo.appointmentRate
                      ? myRateInfo.appointmentRate.toFixed(0)
                      : 0
                  }}%
                </div>
              </div>
              <div class="td">
                <div>客户预约率</div>
                <!-- <div class="t1">{{bestRateInfo.appointmentRate?bestRateInfo.appointmentRate.toFixed(0):0}}%</div> -->
                <div class="t1">78%</div>
              </div>
              <div class="td">
                <div>客户预约率</div>
                <div class="t1">
                  {{
                    meanRateInfo.appointmentRate
                      ? meanRateInfo.appointmentRate.toFixed(0)
                      : 0
                  }}%
                </div>
              </div>
            </div>
            <div class="tab_tr">
              <div class="td first_td"><div class="td_arrived">客户预约率</div></div>
              <div class="td">
                <div>预约到店率</div>
                <div class="t1">
                  {{
                    myRateInfo.appointmentArrivedRate
                      ? Number(myRateInfo.appointmentArrivedRate).toFixed(0)
                      : 0
                  }}%
                </div>
              </div>
              <div class="td">
                <div>预约到店率</div>
                <!-- <div class="t1">{{bestRateInfo.appointmentArrivedRate?Number(bestRateInfo.appointmentArrivedRate).toFixed(0):0}}%</div> -->
                <div class="t1">83%</div>
              </div>
              <div class="td">
                <div>预约到店率</div>
                <div class="t1">
                  {{
                    meanRateInfo.appointmentArrivedRate
                      ? Number(meanRateInfo.appointmentArrivedRate).toFixed(0)
                      : 0
                  }}%
                </div>
              </div>
            </div>
            <div class="tab_tr">
              <div class="td first_td"><div class="td_deal">客户预约率</div></div>
              <div class="td">
                <div>到店成交率</div>
                <div class="t1">
                  {{
                    myRateInfo.arrivedDealRate
                      ? Number(myRateInfo.arrivedDealRate).toFixed(0)
                      : 0
                  }}%
                </div>
              </div>
              <div class="td">
                <div>到店成交率</div>
                <!-- <div class="t1">{{bestRateInfo.arrivedDealRate?Number(bestRateInfo.arrivedDealRate).toFixed(0):0}}%</div> -->
                <div class="t1">90%</div>
              </div>
              <div class="td">
                <div>到店成交率</div>
                <div class="t1">
                  {{
                    meanRateInfo.arrivedDealRate
                      ? Number(meanRateInfo.arrivedDealRate).toFixed(0)
                      : 0
                  }}%
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 转化率  end -->

    <!-- 设置目标 开始 -->
    <glsx-dialog :show="showDialog" title="本月目标设置" @close="closeDialog()">
      <div class="target_box">
        <el-form
          :model="addForm"
          ref="addForm"
          :rules="addFormRules"
          label-width="120px"
        >
          <el-form-item label="预约人数：" prop="appointmentCnt">
            <el-input
              placeholder="请输入"
              v-model.number="addForm.appointmentCnt"
              class="a_input"
            >
              <template slot="append">人</template>
            </el-input>
          </el-form-item>
          <el-form-item label="到店人数：" prop="arrivedCnt">
            <el-input
              placeholder="请输入"
              v-model.number="addForm.arrivedCnt"
              class="a_input"
            >
              <template slot="append">人</template>
            </el-input>
          </el-form-item>
          <el-form-item label="成交人数：" prop="dealCnt">
            <el-input
              placeholder="请输入"
              v-model.number="addForm.dealCnt"
              class="a_input"
            >
              <template slot="append">人</template>
            </el-input>
          </el-form-item>
          <el-form-item label="新成交金额：" prop="dealAmount">
            <el-input
              placeholder="请输入"
              v-model="addForm.dealAmount"
              class="a_input"
            >
              <template slot="append">万</template>
            </el-input>
          </el-form-item>
          <el-form-item label="收款金额：" prop="collectMoney">
            <el-input
              placeholder="请输入"
              v-model="addForm.collectMoney"
              class="a_input"
            >
              <template slot="append">万</template>
            </el-input>
          </el-form-item>
          <el-form-item label="目标赠语：">
            <el-input
              type="textarea"
              resize="none"
              rows="4"
              placeholder="请输入"
              v-model="addForm.giftWords"
              class="a_input"
            >
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveTarget">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
    </glsx-dialog>
    <!-- 设置目标 end -->
  </div>
</template>

<script>
import {
  GETSALETODODATA,
  GETSALEMONTHTARGETPROGRESS,
  GETSALEPERFORMANCERANKING,
  GETSALETODAYDATA,
  GETSALEMONTHDATA,
  GETSALEWEEKDATA,
  GETSALEMONTHCONVERSION,
  SETUPTARGETINFO,
  GET_SALE_DASHBOARD,
  GET_UPTARGET_INFO,
} from "@/http/system";
import { broadcast, deepClone, showToast } from "@/common/util";
import moment from "moment";
import GlsxDialog from "@/components/Dialog/index";
import { Validator } from "@/common/validator";
export default {
  components: {
    GlsxDialog,
  },
  data() {
    return {
      tabActive: "today",
      taskList: [
        {
          icon: "link_05.png",
          name: "待联系客户",
          id: "waitContactedCnt",
          url: "/customer/contact",
        },
        {
          icon: "link_07.png",
          name: "待更新预约",
          id: "expireCustomerCnt",
          url: "/book/expired",
        },
        {
          icon: "link_06.png",
          name: "待回访预约",
          id: "waitReturnVisitCnt",
          url: "/book/visit",
        },
        {
          icon: "link_11.png",
          name: "待提醒预约",
          id: "waitRemindCnt",
          url: "/book/undue",
        },
        {
          icon: "link_14.png",
          name: "今日待跟进",
          id: "todayUnfollowupCnt",
          url: "/customer/today",
        },
        {
          icon: "link_08.png",
          name: "待办提醒",
          id: "waitTodoNoticeCnt",
          url: "/system/todo",
        },
      ],
      linkList: [
        {
          icon: "link_12.png",
          name: "待收尾款",
          id: "waitToCollectCnt",
          url: "/deal/record",
        },
        {
          icon: "link_10.png",
          name: "未成交跟进",
          id: "udOverdueCustomerCnt",
          url: "/customer/unsettled",
        },
        {
          icon: "link_09.png",
          name: "待预约跟进",
          id: "waOverdueCustomerCnt",
          url: "/customer/book",
        },
        {
          icon: "link_13.png",
          name: "查看排班",
          id: "waitToCollectCnt2",
          url: "/scheduling/index",
        },
      ],
      todayList: [
        { name: "新增客户数", num: 32, yesterday: 22, id: "newCustomerCnt" },
        { name: "新增预约数", num: 7, yesterday: 22, id: "appointmentCnt" },
        { name: "应到店预约数", num: 7, yesterday: 22, id: "shouldArrivedCnt" },
        { name: "新增到店数", num: 7, yesterday: 22, id: "arrivedCnt" },
        { name: "新增成交数", num: 7, yesterday: 22, id: "arrivedDealCnt" },
        { name: "新增成交金额", num: 7333, yesterday: 22, id: "dealAmount" },
        { name: "新增收款金额", num: 7333, yesterday: 22, id: "collectMoney" },
        { name: "新增退款金额", num: -100, yesterday: 22, id: "refundMoney" },
        {
          name: "平均客单价",
          num: 8999,
          yesterday: 22,
          id: "averageCustomerUnitPrice",
        },
        {
          name: "线索预约率",
          num: "72%",
          yesterday: 22,
          id: "appointmentRate",
        },
        {
          name: "预约到店率",
          num: "72%",
          yesterday: 22,
          id: "appointmentArrivedRate",
        },
        {
          name: "到店成交率",
          num: "72%",
          yesterday: 22,
          id: "arrivedDealRate",
        },
      ],
      monthDataList: [],
      weekDataList: [],
      value: "",
      todoInfo: {},
      targetInfo: {},
      resultList: [],
      myRateInfo: {},
      bestRateInfo: {},
      meanRateInfo: {},
      dealTime: "",
      updateTime: "",
      month: "",
      showDialog: false,
      addForm: {},
      addFormRules: {
        appointmentCnt: [
          { required: true, message: "请输入预约人数", trigger: "blur" },
          { type: "number", message: "请输入数字", trigger: "blur" },
        ],
        arrivedCnt: [
          { required: true, message: "请输入到店人数", trigger: "blur" },
          { type: "number", message: "请输入数字", trigger: "blur" },
        ],
        dealCnt: [
          { required: true, message: "请输入成交人数", trigger: "blur" },
          { type: "number", message: "请输入数字", trigger: "blur" },
        ],
        dealAmount: [
          { required: true, message: "请输入新成交金额", trigger: "blur" },
          {
            pattern: Validator.TWODECIMAL,
            message: "请输入正确的新成交金额",
            trigger: "blur",
          },
        ],
        collectMoney: [
          { required: true, message: "请输入收款金额", trigger: "blur" },
          {
            pattern: Validator.TWODECIMAL,
            message: "请输入正确的收款金额",
            trigger: "blur",
          },
        ],
      },
      orderType: 2,
      iconList: {
        1: require("@/assets/images/icon_one.png"),
        2: require("@/assets/images/icon_two.png"),
        3: require("@/assets/images/icon_three.png"),
        4: require("@/assets/images/icon_four.png"),
        5: require("@/assets/images/icon_five.png"),
      },
      thList: [
        { name: "预约", id: 1, active: false, filed: "appointmentCnt" },
        { name: "成交", id: 2, active: false, filed: "dealAmount" },
        { name: "收款", id: 3, active: false, filed: "collectMoney" },
      ],
      salesList: [],
      saleSummary: {},
      staffInfo: {},
      salesForm: {},
    };
  },
  mounted() {
    this.updateTime = moment().format("yyyy/MM/DD HH:mm");
    this.month = moment().format("MM");
    this.dealTime = moment().format("yyyy-MM");
    this.getTodoData();
    this.getMonthTarget();
    this.getResults();
    this.getToday();
    this.getMonthData();
    this.getMonthRate();
    this.getWeekData();
    this.getSales();
  },
  methods: {
    // 获取代办通知数据
    getTodoData() {
      let _this = this;
      GETSALETODODATA().then((res) => {
        _this.todoInfo = res.data || {};
      });
    },

    // 新增客户
    addCustomer() {
      broadcast("customer.add");
    },

    // 新增预约
    addBook() {
      broadcast("customer.add.book");
    },

    // 收款变动
    addCollect() {
      broadcast("customer.collect.add", { status: 4, title: "收款变动" });
    },

    // 页面跳转
    linkUrlEvent(row) {
      let options = {};
      options.num = this.todoInfo[row.id];
      if (row.id == "waitToCollectCnt") {
        options.dealTypes = "2,3";
      }
      this.$router.push({ path: row.url, query: options });
    },

    // 获取本月目标数据
    getMonthTarget() {
      GETSALEMONTHTARGETPROGRESS().then((res) => {
        let obj = res.data || {};
        let _message = this.showGift(obj.giftWords);
        obj.giftWordsMessage = _message;
        this.targetInfo = obj;
      });
    },

    // 获取本月业绩排行榜
    getResults() {
      let _type = this.orderType;
      let oParams = {};
      oParams.orderType = _type;

      let n = this.thList.find((k) => k.id == _type);

      if (n) {
        oParams.orderDirection = n.active ? "ASC" : "DESC";
        oParams.orderField = n.filed;
      }

      GETSALEPERFORMANCERANKING(oParams).then((res) => {
        let _obj = res.data || {};
        this.resultList = _obj.rankingList || [];
        this.staffInfo = _obj.rankingStaff || {};
      });
    },

    // 获取今日数据
    getToday() {
      GETSALETODAYDATA().then((res) => {
        let obj = res.data || [];
        let t = obj[0] ? obj[0] : [];
        let y = obj[1] ? obj[1] : [];
        this.todayList.map((k) => {
          k.num = t[k.id];
          k.yesterday = y[k.id];
          return k;
        });
      });
    },

    // 获取本周数据
    getWeekData() {
      let _this = this;
      GETSALEWEEKDATA().then((res) => {
        let list = deepClone(_this.todayList);
        let obj = res.data || [];
        let t = obj[0] ? obj[0] : [];
        let y = obj[1] ? obj[1] : [];
        list.map((k) => {
          k.num = t[k.id];
          k.yesterday = y[k.id];
          return k;
        });
        _this.weekDataList = list;
      });
    },

    // 获取本月数据
    getMonthData() {
      let _this = this;
      GETSALEMONTHDATA().then((res) => {
        let list = deepClone(_this.todayList);
        let obj = res.data || [];
        let t = obj[0] ? obj[0] : [];
        let y = obj[1] ? obj[1] : [];
        list.map((k) => {
          k.num = t[k.id];
          k.yesterday = y[k.id];
          return k;
        });
        _this.monthDataList = list;
      });
    },

    // 获取本月转化率
    getMonthRate() {
      let oParams = {};
      oParams.month = this.dealTime;
      GETSALEMONTHCONVERSION(oParams).then((res) => {
        let list = res.data || [];
        this.myRateInfo = list[0] || {};
        this.bestRateInfo = list[1] || {};
        this.meanRateInfo = list[2] || {};
      });
    },

    // 打开弹框
    openDialog() {
      GET_UPTARGET_INFO().then((res) => {
        let obj = res.data || {};
        this.addForm = obj || {};
        console.log(res);
      });
      this.showDialog = true;
    },

    // 关闭弹框
    closeDialog() {
      this.$refs.addForm.clearValidate();
      this.showDialog = false;
      this.addForm = {};
    },

    // 保存目标
    saveTarget() {
      let _this = this;
      let oParams = deepClone(_this.addForm);
      _this.$refs.addForm.validate((valid) => {
        if (!valid) {
          return false;
        }
        SETUPTARGETINFO(oParams).then((res) => {
          if (res.code == 200) {
            showToast({
              message: "保存成功",
              type: "success",
            });
            _this.closeDialog();
            _this.getMonthTarget();
          }
        });
      });
    },

    // 数字单位处理
    showNumber(str) {
      let o = Number(str || 0);
      return Math.round(o / 10000);
    },

    // 处理月份展示
    showRateTime(str) {
      if (!str) {
        return "";
      }
      let m = moment(str).format("M");
      return m;
    },

    // 切换本月业绩排行榜
    thEvent(row, index) {
      row.active = !row.active;
      this.orderType = row.id;
      this.$set(this.thList, index, row);
      this.getResults();
    },

    // 获取销售看板
    getSales() {
      let params = deepClone(this.salesForm);
      GET_SALE_DASHBOARD(params).then((res) => {
        console.log(res);
        let _obj = res.data || {};
        this.salesList = _obj.list || [];
        this.saleSummary = _obj.summary || {};
      });
    },

    // 处理列表
    getUserList(list) {
      let arr = deepClone(list);
      if (!arr || arr.length < 0) {
        return [];
      }
      if (arr.length <= 4) {
        return arr;
      }
      if (arr.length > 4) {
        arr.length = 4;
        return arr;
      }
    },

    // 随机展示赠语
    showGift(list) {
      if (!list || list.length < 0) {
        return "";
      }
      let len = list.length;
      let idx = Math.floor(Math.random() * len);
      console.log(idx);
      let str = list[idx] || {};
      if (!str.giftWords) {
        str = list[Math.floor(Math.random() * len)] || {};
      }
      let _messgae = `${str.username}赠语：${str.giftWords}`;
      return _messgae;
    },

    // 展示合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      let list = [
        "todayAppointCnt",
        "todayNewAppointCnt",
        "todayFollowCnt",
        "todayFollowPeople",
        "monthAppointCnt",
        "monthFollowCnt",
        "monthFollowPeople",
        "averageDailyFollowupPeople",
      ];
      let o = this.saleSummary;
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        let idx = list.indexOf(column.property);
        if (idx >= 0) {
          sums[index] = o[column.property] ? o[column.property].toFixed(1) : 0;
        } else {
          sums[index] = "";
        }
      });

      return sums;
    },

    // 获取前5条数据
    getPreFive(list) {
      let arr = deepClone(list);
      if (!arr || arr.length == 0) {
        return [];
      }
      if (arr.length <= 5) {
        return arr;
      }

      if (arr.length > 5) {
        arr.length = 5;
      }
      return arr;
    },

    // 获取后5条数据
    getLastFive(list) {
      let arr = deepClone(list);
      let len = arr.length;
      let n = [];
      if (!arr || len <= 5) {
        return [];
      }
      if (len > 5 && len <= 10) {
        n = arr.slice(5);
      }

      if (len > 10) {
        n = arr.slice(len - 5);
      }
      return n;
    },

    // 获取下标
    getIndex(row) {
      let list = this.resultList;
      let idx = list.findIndex((k) => k.id == row.id);
      return idx + 1;
    },

    // 监听表格排序
    sortChange({ column, prop, order }) {
      let o = { orderField: prop };
      this.salesForm.orderField = prop;
      if (order == "ascending") {
        this.salesForm.orderDirection = "ASC";
      } else {
        this.salesForm.orderDirection = "DESC";
      }
      this.getSales();
    },

    // 控制进度条数字展示
    showProcess(num) {
      let _process = 0;
      if (num) {
        _process = Number(targetInfo.appointmentReachRate.toFixed(0));
      }
      return _process;
    },

    // 控制单位展示
    showUnit(id) {
      let unit = "";
      let ids = [
        "appointmentRate",
        "appointmentArrivedRate",
        "arrivedDealRate",
      ];
      let idx = ids.findIndex((k) => k == id);
      if (idx >= 0) {
        unit = "%";
      }
      return unit;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "index.scss";

.target_box {
  .a_input {
    width: 80%;
  }
}

.task_tips {
  font-size: 14px;
  color: #999;
  margin: 10px 0;
  padding: 0 23px 0 53px;
  cursor: pointer;

  .tag {
    margin: 0 4px;
  }
}

.task_tips_popover {
  .tag {
    margin: 4px;
  }
}

.plan_box {
  .task_tips {
    padding: 0 23px 0 26px;
  }
}

.staff_tips {
  font-size: 14px;
  color: #999;
  margin: 10px 6px 10px 40px;
}
</style>
